<?php

class ChatController extends Controller {
    protected $allowed = array('administrator' , 'member');

    public static $STATUS_UNREAD = 0;
    public static $STATUS_READ = 1;

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        if ($this->isAllowed()) {
            $chats = Model::loadRowsFromQuery("SELECT * FROM `chat` WHERE `status` = " . self::$STATUS_UNREAD . " AND `recipient_id` = ".$this->auth->id.";", 'ChatModel');
            $s = array();
            foreach ($chats as $chat) {
                $s[$chat->getSender()->id] = true;
            }

            $senders = array();
            foreach ($s as $sender => $val) {
                $senders[] = Model::factory('auth' , $sender);
            }

            $this->render('chat/index' , array('senders' => $senders));
        }
    }

    public function room($user_id) {
        $user = Model::factory('auth' , $user_id);

        if ($user->loaded() && $this->isAllowed()) {
            $this->render('chat/room' , array('sender' => $this->auth , 'recipient' => $user));
        }
    }

    public function send($recipient_id) {
        $recipient = Model::factory('auth' , $recipient_id);
        if ($this->isAllowed() && $recipient->loaded() && $_POST['content'] != '') {
            $chat = Model::factory('chat');
            $chat->sender_id = $this->auth->id;
            $chat->recipient_id = $recipient->id;
            $chat->content = $_POST['content'];
            $chat->timestamp = time();
            $chat->status = self::$STATUS_UNREAD;
            $chat->save();
        }
    }

    public function countUnreadChat() {
        if ($this->isAllowed()) {
            $chats = Model::loadRowsFromQuery("SELECT * FROM `chat` WHERE `status` = " . self::$STATUS_UNREAD . " AND `recipient_id` = ".$this->auth->id.";", 'ChatModel');
            $c = array();
            foreach ($chats as $chat)
                $c[$chat->getSender()->id] = true;
            echo count($c);
        }
    }

    public function getUnreadChat() {
        if ($this->isAllowed()) {
            $chats = Model::loadRowsFromQuery("SELECT * FROM `chat` WHERE `status` = " . self::$STATUS_UNREAD . " AND `recipient_id` = ".$this->auth->id.";", 'ChatModel');
            $c = array();
            foreach ($chats as $chat) {
                $c[] = array('fullname' => $chat->getSender()->fullname , 'content' => $chat->content);
                $chat->status = self::$STATUS_READ;
                $chat->save();
            }
            echo json_encode($c);
        }
    }

}

?>
